<template>
  <el-table :height="height" :data="list" border stripe>
    <el-table-column prop="id" label="部门ID"></el-table-column>
    <el-table-column prop="name" label="部门名称"></el-table-column>
    <el-table-column prop="location" label="部门所在地"></el-table-column>
    <el-table-column label="操作" width="220" align="center">
      <template #default="scope">
        <el-button type="primary"
                   :icon="Edit"
                   size="default"
                   @click="handleEditClick(scope.row)">
          编辑
        </el-button>
        <el-button type="danger"
                   :icon="Delete"
                   size="default"
                   @click="handleDeleteClick(scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

</template>

<script setup lang="ts">
import { Delete, Edit } from '@element-plus/icons-vue'
import { onMounted, toRefs } from 'vue'
import type { DepartmentInfo } from '@/hooks/department.hook.type.ts'
import { emitter, useDepartmentStore } from '@/stores/department.store.ts'
import { storeToRefs } from 'pinia'
import { useDepartmentTable } from '@/hooks/department.hook.ts'

const store = useDepartmentStore()
const { table } = storeToRefs(store)
const {
  height, list
} = toRefs(table.value)
const {
  fetchDataForList,
  chooseCurrentDepartment,
  deleteCurrentDepartment
} = useDepartmentTable()

const {} = store

function handleEditClick(row: DepartmentInfo) {
  chooseCurrentDepartment(row)
  emitter.emit('table_edit_btn_clicked')
}

function handleDeleteClick(row: DepartmentInfo) {
  deleteCurrentDepartment(row.id).then(() => {
    emitter.emit('table_department_deleted')
  })
}

function search() {
  fetchDataForList().then(() => {
    height.value = window.innerHeight - 230
  })
}

function remove() {
}

onMounted(() => {
  search()
  emitter.on('search_search_btn_clicked', search)
  emitter.on('search_reset_btn_clicked', search)
  emitter.on('pagination_page_size_changed', search)
  emitter.on('pagination_current_page_changed', search)
  emitter.on('table_delete_btn_clicked', remove)
  emitter.on('table_department_deleted', search)
  emitter.on('dialog_department_added', search)
  emitter.on('dialog_department_updated', search)
})
</script>

<style scoped lang="scss">

</style>
